package com.timedomain.him.remake.utils;

import com.timedomain.him.remake.Program;

import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {

    public static List<String> listFiles(String dir){
        List<String> f = new ArrayList<>();
        for (DataPackManager.DataPackEntry entry:
             Program.getDataEntries(null)) {
            if(entry.path.startsWith(dir)){
                f.add(entry.path);
            }
        }
        return f;
    }

    public static List<String> listFiles(String dir, FilenameFilter filter){
        List<String> f = new ArrayList<>();
        for (DataPackManager.DataPackEntry entry:
                Program.getDataEntries(null)) {
            if(entry.path.startsWith(dir) && filter.accept(null,entry.path)){
                f.add(entry.path);
            }
        }
        return f;
    }

    public static String pickRandomOneOgg(String rootPath){
        List<String> files = listFiles(rootPath,(dir,file)->file.toLowerCase().endsWith(".ogg"));
        if(files.isEmpty()){return null;}
        int rndint = (int) (Math.random() * files.size());
        if(rndint >= files.size()){
            rndint = files.size();
        }
        return files.get(rndint);
    }


    public static String pathCombine(String... strs){
        StringBuilder sb = new StringBuilder();
        for (String str : strs) {
            String onestr = str;
            if (sb.length() > 0) {
                sb.append('/');
            }
            if (onestr.startsWith("/")) {
                onestr = onestr.substring(1);
            }
            if (onestr.endsWith("/")) {
                onestr = onestr.substring(0, onestr.length() - 1);
            }
            sb.append(onestr);
        }
        return sb.toString();
    }

    public static String getParentPath(String file){
        return file.substring(0,file.lastIndexOf('/'));
    }

    public static List<String> getAllNightStories(){
        String rootPath = pathCombine("companions","story");
        String ignoreFlag = ".ignoredInNightMode";
        List<String> stories = listFiles(rootPath,(dir,file)->file.toLowerCase().endsWith(".ogg"));
        List<String> results = new ArrayList<>();
        for (String oneStory : stories) {
            if(Program.getDataPack(null).containsKey(
                    pathCombine(getParentPath(oneStory),ignoreFlag)
            )){
                continue;
            }
            results.add(oneStory);
        }
        return results;
    }

    public static String getFileNameWithoutExtension(String path){
        String name = path.substring(path.lastIndexOf('/')+1);
        return name.substring(0,name.lastIndexOf("."));
    }

}
